from django.shortcuts import render, redirect, reverse
from django.http import HttpResponse
from django.views.decorators.http import require_http_methods
from photoapp.models import Photo
from django.contrib import messages
from django.core.paginator import Paginator
import shortuuid, os
from PIL import Image

# Create your views here.

def index(request, page_index):
    try:
        if page_index == '':
            page_index = 1
        photos = Photo.objects.all()
        p = Paginator(photos, 10)
        page = p.page(page_index)
        p_range = p.page_range
        context = {
            'photos': page.object_list,
            'page_num': p_range
        }
        return render(request, 'photoapp/index.html', context=context)
    except Exception as error:
        return HttpResponse(error)

@require_http_methods(['GET', 'POST'])
def add_photo(request):
    try:
        if request.method == "GET":
            return render(request, 'photoapp/add_photo.html')
        else:
            title = request.POST.get('title')
            file = request.FILES.get('file')
            if not title or not file:
                messages.info(request, '请提交完整数据')
                return redirect(reverse('add_photo'))

            filepath, filepath_s = photo_handle(request)
            Photo.objects.create(title=title, filepath=filepath, filepath_s=filepath_s)
            return redirect(reverse('index'))
    except Exception as error:
        return HttpResponse(error)

@require_http_methods(['GET', 'POST'])
def edit_photo(request, photo_id):
    try:
        if request.method == 'GET':
            photo = Photo.objects.get(pk=photo_id)
            context = {
                'photo': photo
            }
            return render(request, 'photoapp/edit_photo.html', context=context)
        else:
            title = request.POST.get('title')
            file = request.FILES.get('file')
            photo_id = request.POST.get('photo_id')
            if not title or not file:
                messages.info(request, '请提交完整数据')
                return redirect(reverse('edit_photo'))

            filepath, filepaths = photo_handle(request)
            Photo.objects.filter(pk=photo_id).update(title=title, filepath=filepath, filepath_s=filepaths)
            return redirect(reverse('index'))
    except Exception as error:
        return HttpResponse(error)

def delete_photo(request, photo_id):
    try:
        photo = Photo.objects.get(pk=photo_id)
        filepath = photo.filepath
        filepath_s = photo.filepath_s
        if os.path.isfile(filepath):
            os.remove(filepath)
        if os.path.isfile(filepath_s):
            os.remove(filepath_s)
        photo.delete()
        return redirect(reverse('index'))
    except Exception as error:
        return HttpResponse(error)

def photo_handle(request):
    file = request.FILES.get('file')
    unique = shortuuid.uuid()
    filename = unique + '.' + file.name.split('.').pop()
    filename_s = unique + '_s.' + filename.split('.').pop()
    filepath =  os.path.join('media', filename)
    filepath_s = os.path.join('media', filename_s)

    with open(filepath, 'wb') as fp:
        for chunk in file.chunks():
            fp.write(chunk)

    img = Image.open(filepath)
    img.thumbnail((50, 50))
    img.save(filepath_s)

    return filepath, filepath_s